package libra.init;

import java.util.EnumSet;

import javax.servlet.DispatcherType;
import javax.servlet.FilterRegistration;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRegistration.Dynamic;

import org.springframework.web.WebApplicationInitializer;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.filter.CharacterEncodingFilter;
import org.springframework.web.servlet.DispatcherServlet;

public class MainStater implements WebApplicationInitializer {
	@Override
	public void onStartup(ServletContext servletContext) throws ServletException {
		System.out.println("配置SpringMVC容器");
		// 手动配置spring的ioc容器
        AnnotationConfigWebApplicationContext ctx = new AnnotationConfigWebApplicationContext();
        // 制定配置类
        ctx.register(Config.class);  
        ctx.setServletContext(servletContext);    
        
        // 创建注册dispatcher
        Dynamic servlet = servletContext.addServlet("dispatcher", new DispatcherServlet(ctx));
        servlet.addMapping("/");  
        servlet.setLoadOnStartup(1);
        
        // 手动注册编码集filter
        // SpringMVC乱码处理
        CharacterEncodingFilter characterEncodingFilter = new CharacterEncodingFilter("UTF-8");
        FilterRegistration encodeFilter = servletContext.addFilter("encodeFilter", characterEncodingFilter);
        encodeFilter.addMappingForUrlPatterns(EnumSet.of(DispatcherType.REQUEST), true, "/*");  
	}
}
